'''
Created on 8 oct. 2012

@author: MARTINS-N
'''

import utils
import __builtin__
import sys
import threading
import database
import pyfus
import traceback
from socket import *

class login_client(object):

    def __init__(self, sock):
        self.sock = sock
        self.key = utils.random_str(32)
        self.logon_state = 1
        self.account = None
        threading.Thread(None, self.receiveThread, None, (), {}).start()
        
        self.send('HC' + self.key)
        pass
    
    def send(self, packet):
        self.sock.send(packet + '\x00')
        print 'Send packet : ' + packet
        pass
    
    def receiveThread(self):
        while(True):
            data = self.sock.recv(4096).replace('\x0a', '')
            #print 'Received data from client : ' + data
            for packet in data.split('\x00'):
                if(packet != ''):
                    try:                         
                        print 'Received packet from client : ' + packet
                        self.handle(packet)
                        pass
                    except Exception:
                        print 'Error when handle packet' + traceback.format_exc()
                        pass
                pass
            pass
        pass
    
    def sendServerState(self):
        packet = "AH1;1;75;1"
        # packet.Append(server.ID).Append(";").Append((int)server.State).Append(";").Append((server.ID *75).ToString()).Append(";1");
        self.send(packet)
        pass
    
    def sendCharacterCount(self):
        self.send("AxK31600000000000|1,0")
        pass
    
    def handle(self, packet):
        if(self.logon_state == 1):
            self.handleVersion(packet)
        elif(self.logon_state == 2):
            self.handleLogin(packet)
            pass
        elif(self.logon_state == 3):
            self.handleServersList(packet)
            pass
        pass
    
    def handleVersion(self, packet):
        if(packet == "1.29.1"):
            print '>> Good dofus version for client !'
            self.logon_state = 2
        else:
            print '>> Wrong dofus version for client .. ' + packet
            pass
        pass
    
    def handleLogin(self, packet):
        username = packet.split('#1')[0]
        password = '#1' + packet.split('#1')[1]
        print '>> Try to login with creditential u=' + username + ", p=" + password
        account = pyfus.DB.get_account(username)
        if(account != None):
            epass = utils.pwd_encode(account.password, self.key)
            if(password == epass):
                self.logon_state = 3
                self.account = account
                self.send("Ad" + self.account.pseudo)
                self.send("Ac0")
                self.sendServerState()
                self.send("AlK{0:d}".format(self.account.rank) )
                print '>> Client logged with account ' + account.username
                pass
            else:
                self.logon_state = -1
                self.send("AlEx")
                pass
            pass
        else:
            self.logon_state = -1
            self.send("AlEx")
            pass
        pass
        
    def handleServersList(self, packet):
        if(packet[0:2] == "Ax"):
            self.sendCharacterCount()
            pass
        elif(packet[0:2] == "AX"):
            self.handleServerSelect(packet)
            pass
        pass
    
    def handleServerSelect(self, packet):
        ticket = utils.random_str(32)
        pyfus.SWITCH_TICKETS.append(switch_ticket(self.account, ticket))#Add ticket for retrieve the client in the game server
        
        self.send("AYK" + pyfus.SETTINGS['GameHost'] + ":" + str(pyfus.SETTINGS['GamePort']) + ";" + ticket)
        print '>> Switch player ' + self.account.username + ' on the game server'
        pass
    
    pass

class switch_ticket(object):
    
    def __init__(self, account, ticket):
        self.account = account
        self.ticket = ticket
        pass
    
    pass